package com.icbc.open.chengdu.demo.ui;

import com.icbc.api.IcbcApiException;
import com.icbc.api.IcbcConstants;
import com.icbc.api.UiIcbcClient;
import com.icbc.api.request.EaccountManageRequestV1;

import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 模拟http服务器，实现H5接口调用实例
 * @author  zhangxc
 */
public class EaccountManageTest {
    /**
     * 接口地址：
     * 测试环境为：https://apipcs3.dccnet.com.cn/ui/eaccount/manage/V1
     * 生产环境为：https://gw.open.icbc.com.cn/ui/eaccount/manage/V1
     */
    private static final String API_URL = "https://apipcs3.dccnet.com.cn/ui/eaccount/manage/V1";
    /**
     * 联系工行提供
      */
    private static final String APP_ID = "xxx";
    /**
     * 使用sdk中bin文件夹下工具脚本生成
     */
    private static final String AES_KEY = "xxx";
    /**
     *  使用sdk中bin文件夹下工具脚本生成（生成的公钥发工行）
     */
    private static final String RSA_PRI_KEY = "xxx";
	
    public static void main(String[] args) {
        try {
            /*监听端口号，只要是8888就能接收到*/
            ServerSocket ss = new ServerSocket(8888);
            while (true) {
                /*实例化客户端，固定套路，通过服务端接受的对象，生成相应的客户端实例*/
                Socket socket = ss.accept();
                /*发送回执*/
                PrintWriter pw = new PrintWriter(socket.getOutputStream());
                pw.println("HTTP/1.1 200 OK");
                pw.println("Content-type:text/html");
                pw.println();
                pw.println(requestEaccountH5());
                pw.flush();
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 生成返回给浏览器的form表单数据，浏览器接收到form数据后自动提交
     * @return 返回浏览器数据
     * @throws IcbcApiException icbc异常
     */
    private static String requestEaccountH5() throws IcbcApiException {
        EaccountManageRequestV1.EaccountManageRequestBizV1 biz = new EaccountManageRequestV1.EaccountManageRequestBizV1();
        //使用用户身份证号或者微信的openID或者可以唯一对应用户的编号
        biz.setUserId("511321189810289834");
        biz.setCorpAppid(APP_ID);
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        biz.setOrderTimeStamp(sdf.format(d));
        UiIcbcClient client = new UiIcbcClient(APP_ID, IcbcConstants.SIGN_TYPE_RSA, RSA_PRI_KEY,
                IcbcConstants.CHARSET_UTF8,IcbcConstants.ENCRYPT_TYPE_AES, AES_KEY);
        EaccountManageRequestV1 request = new EaccountManageRequestV1();
        request.setServiceUrl(API_URL);
        request.setBizContent(biz);
        return client.buildPostForm(request);
    }
}
